<template>
  <div class="history">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>历史记录</h3>
        </div>
      </template>
      <div class="filters">
        <el-form :inline="true" :model="filters" size="default">
          <el-form-item label="年级">
            <el-select v-model="filters.grade" placeholder="全部年级" style="width: 160px">
              <el-option :value="undefined" label="全部" />
              <el-option v-for="g in grades" :key="g.id" :value="g.level" :label="g.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
              v-model="filters.range"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="applyFilters">筛选</el-button>
            <el-button @click="resetFilters">重置</el-button>
            <el-button @click="exportCSV">导出CSV</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="content">
        <el-table :data="items" v-loading="loading" style="width: 100%" size="large" @sort-change="onSortChange">
          <el-table-column prop="finishedAt" label="时间" min-width="180" sortable="custom" />
          <el-table-column prop="score" label="得分" width="100" sortable="custom" />
          <el-table-column prop="durationSec" label="用时(秒)" width="120" sortable="custom">
            <template #default="scope">{{ formatDuration(scope.row.durationSec) }}</template>
          </el-table-column>
          <el-table-column prop="wrongCount" label="错题数" width="100" sortable="custom" />
          <el-table-column label="当时建议" min-width="320">
            <template #default="scope">
              <span class="suggest">{{ scope.row.suggestions.join('；') }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="pager">
          <el-pagination
            background
            layout="prev, pager, next, sizes, total"
            :current-page="page.page"
            :page-size="page.pageSize"
            :page-sizes="[10,20,50]"
            :total="page.total"
            @current-change="onPageChange"
            @size-change="onSizeChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import mathTestApi, { type Grade } from '@/api/mathTest'

type HistoryItem = {
  id: number
  finishedAt: string
  score: number
  durationSec: number
  wrongCount: number
  suggestions: string[]
}

type Filters = {
  grade?: number
  range?: [string, string] | null
}

type PageState = { page: number; pageSize: number; total: number }

const loading = ref(false)
const raw = ref<HistoryItem[]>([])
const grades = ref<Grade[]>([])
const filters = ref<Filters>({ grade: undefined, range: null })
const page = ref<PageState>({ page: 1, pageSize: 10, total: 0 })
const sort = ref<{ by?: string; order?: 'asc' | 'desc' }>({})
const userId = ref<number | undefined>(undefined)

import { useRoute } from 'vue-router'
const route = useRoute()

onMounted(async () => {
  await Promise.all([loadGrades()])
  const uid = route.query.user_id ? Number(route.query.user_id) : undefined
  if (uid) userId.value = uid
  await fetchList()
})

async function loadGrades() {
  grades.value = await mathTestApi.getGrades()
}

async function fetchList() {
  loading.value = true
  try {
    const params: any = { page: page.value.page, pageSize: page.value.pageSize }
    if (userId.value) params.user_id = userId.value
    if (filters.value.grade) params.grade = filters.value.grade
    if (filters.value.range && filters.value.range.length === 2) {
      params.start = filters.value.range[0]
      params.end = filters.value.range[1]
    }
    if (sort.value.by && sort.value.order) {
      params.sortBy = sort.value.by
      params.sortOrder = sort.value.order
    }
    const res = await mathTestApi.getHistoryList(params)
    raw.value = res.items
    page.value.total = res.total
  } finally {
    loading.value = false
  }
}

function applyFilters() {
  fetchList()
}

function resetFilters() {
  filters.value = { grade: undefined, range: null }
  fetchList()
}

function exportCSV() {
  const header = ['时间','得分','用时','错题数','当时建议']
  const rows = raw.value.map(i => [
    i.finishedAt,
    i.score,
    formatDuration(i.durationSec),
    i.wrongCount,
    (i.suggestions || []).join('；')
  ])
  const csv = [header, ...rows].map(r => r.map(field => `"${String(field).replace(/"/g,'""')}"`).join(',')).join('\n')
  const blob = new Blob(["\uFEFF" + csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = '历史记录.csv'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

function onPageChange(p: number) {
  page.value.page = p
  fetchList()
}

function onSizeChange(ps: number) {
  page.value.pageSize = ps
  page.value.page = 1
  fetchList()
}

function onSortChange({ prop, order }: any) {
  sort.value.by = prop
  sort.value.order = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : undefined
  page.value.page = 1
  fetchList()
}

const items = computed(() =>
  raw.value.map(i => ({
    ...i,
    durationText: formatDuration(i.durationSec)
  }))
)

function formatDuration(sec: number) {
  const m = Math.floor(sec / 60)
  const s = sec % 60
  return `${m}分${s}秒`
}
</script>

<style scoped>
.history {
  padding: 24px;
  max-width: 960px;
  margin: 0 auto;
}
.filters {
  margin-bottom: 12px;
}
.suggest {
  color: #606266;
}
.pager {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>
